package util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import Application.HRTApplication;

public class CommonMethod {

	public static final boolean DEBUG_HUI = true;
	public static final boolean DEBUG_ZHI = true;
    private static WindowManager windowmanager;
    private static View passwdview;

    public static void hidePassWdPadView(){
        if (windowmanager!=null&&passwdview!=null){
            windowmanager.removeView(passwdview);
        }
    }

    private ConfirmListener confirmListener;
    public interface ConfirmListener{
        public void confirm(String result);
        public void cancel();
    }
    public void setOnConfirmListener(ConfirmListener confirmListener){
        this.confirmListener = confirmListener;
    }


    public static void showToastMsg(Context context,  String message){
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
   /* public  void showPassWdPadView(final Activity context,EditText v){
        DigitPasswordKeyPad dpk = new DigitPasswordKeyPad(context);
        passwdview = dpk.setup(v,confirmListener);
        context.runOnUiThread(new Runnable() {
            public void run() {
                // 让一个视图浮动在你的应用程序之上
                windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                WindowManager.LayoutParams layoutparams = new WindowManager.LayoutParams(-1, -1, WindowManager.LayoutParams.FIRST_SUB_WINDOW, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.RGBA_8888);
                layoutparams.gravity = Gravity.BOTTOM;
                passwdview.findViewById(R.id.transpwdpdpanel).getBackground().setAlpha(140);
                windowmanager.addView(passwdview, layoutparams);
            }
        });
    }
*/
	
	@SuppressLint("NewApi")
	public static Uri imageuri(Uri uri, Activity activity) {

		if(android.os.Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.KITKAT){
			return uri;
		}
		String path = "";

		if (DocumentsContract.isDocumentUri(activity, uri)) {

		String wholeID = DocumentsContract.getDocumentId(uri);

		String id = wholeID.split(":")[1];

		String[] column = { MediaStore.Images.Media.DATA };

		String sel = MediaStore.Images.Media._ID + "=?";

		Cursor cursor = activity.getContentResolver().query(

		MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,

		new String[] { id }, null);

		int columnIndex = cursor.getColumnIndex(column[0]);

		if (cursor.moveToFirst()) {

		path = cursor.getString(columnIndex);

		}

		cursor.close();

		} else {

		String[] projection = { MediaStore.Images.Media.DATA };

		Cursor cursor = activity.getContentResolver().query(uri,

		projection, null, null, null);

		int column_index = cursor

		.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		path = cursor.getString(column_index);

		}
		uri = Uri.fromFile(new File(path));
		return uri;
		} 
	
	
	
	/**
	 * 是否为空
	 * 
	 * @param dostr
	 * @return
	 */
	public static boolean isEmpty(String dostr) {
		if (dostr == null || "".equals(dostr.trim()) || "null".equals(dostr) || dostr == " ") {
			return true;
		}
		return false;
	}

	/**
	 * 判断网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		} else {
			// 如果仅仅是用来判断网络连接　　　　　　
			// 则可以使用 cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static String getMyCurrentTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		return formatter.format(curDate);

		/*
		 * 获取年月日当前时间 SimpleDateFormat sDateFormat = new
		 * SimpleDateFormat("yyyy-MM-dd   hh:mm:ss"); String date =
		 * sDateFormat.format(new java.util.Date());
		 */

		/*
		 * 如果想获取当前的年月,则可以这样写(只获取时间或秒种一样): SimpleDateFormat sdf=new
		 * SimpleDateFormat("yyyy-MM"); String date=sdf.format(new
		 * java.util.Date());
		 */

		/*
		 * 当然还有就是可以指定时区的时间(待):
		 * df=DateFormat.getDateTimeInstance(DateFormat.FULL,
		 * DateFormat.FULL,Locale.CHINA); System.out.println(df.format(new
		 * Date()));
		 */
	}

	public static void closeKeyboard(Activity context) {

		try {
			InputMethodManager m = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
			if (m.isActive()) {
				((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		} catch (Exception e) {
		}
	}

	/**
	 * 从相册选择图片
	 * 
	 * @param activity
	 * @param requestCode
	 */
	public static void pickImageFromPhoto(Activity activity, int requestCode) {

		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		activity.startActivityForResult(intent, requestCode);

	}

	public static void pickImageFromPhotoForFragment(Fragment fragment, int requestCode) {

		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		fragment.startActivityForResult(intent, requestCode);

	}

	/**
	 * 拍照
	 * 
	 * @param activity
	 * @param requestCode
	 *//*
	public static void pickImageFromCamera(Activity activity, int requestCode) {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(AddImageUtil.DEFAULT_IMAGE_PATH);

		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/

	/*	// 下面这句指定调用相机拍照后的照片存储的路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		intent.putExtra("return-data", false);
		activity.startActivityForResult(intent, requestCode);
	}

	public static void pickImageFromCameraForFragment(Fragment activity, int requestCode) {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(AddImageUtil.DEFAULT_IMAGE_PATH);

		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// 下面这句指定调用相机拍照后的照片存储的路径
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		intent.putExtra("return-data", false);
		activity.startActivityForResult(intent, requestCode);
	}*/

	/**
	 * 获取可以使用的缓存目录
	 * 
	 * @param context
	 * @param uniqueName
	 *            目录名称
	 * @return
	 */
	public static File getDiskCacheDir(Context context, String uniqueName) {
		final String cachePath = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ? getExternalCacheDir(context).getPath() : getPhoneCacheDir(context).getPath();

		File file = new File(cachePath + File.separator + uniqueName);
		if (!file.exists()) {
			file.mkdirs();
		}
		if (!file.canWrite()) {
			chmod("777", cachePath);
			// file.setWritable(true);
		}
		return file;
	}

	/**
	 * 获取程序外部的缓存目录
	 * 
	 * @param context
	 * @return
	 */
	public static File getExternalCacheDir(Context context) {
		final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
		return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
	}

	/**
	 * 获取程序内部的缓存目录
	 * 
	 * @param context
	 * @return
	 */
	public static File getPhoneCacheDir(Context context) {
		final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
		return new File(context.getCacheDir().getPath() + cacheDir);
	}

	/**
	 * 改变文件夹权限
	 * 
	 * @param permission
	 * @param path
	 */
	public static void chmod(String permission, String path) {
		try {
			String command = "chmod " + permission + " " + path;
			Runtime runtime = Runtime.getRuntime();
			runtime.exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回原照片的地址 从相册回来后，获取该图文件地址 可以直接去头像裁剪
	 * eg:/mnt/sdcard/DCIM/Camera/C360_2013-01-07-17-26-44_org.jpg
	 * 
	 * @param context
	 * @param uri
	 * @return
	 */
	public static String getPathFromPhoto(Context context, Uri uri) {
		String img_path = null;
		if (uri.toString().contains("content")) {
			Cursor cursor = null;
			try {
				
				//从mediastore的uri中获得文件名和路径
				String[] proj = { MediaStore.Images.Media.DATA };
				//获取本机中的所有图片
				android.support.v4.content.CursorLoader cursorLoader = new 
						android.support.v4.content.CursorLoader(context, uri, proj, null, null, null);
				Cursor actualimagecursor = cursorLoader.loadInBackground();
				//返回指定列的名称
				int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				//定位为第一行
				actualimagecursor.moveToFirst();
				img_path = actualimagecursor.getString(actual_image_column_index);
				System.out.println("-----+++++++++=-------img_path-----------"+img_path);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (cursor != null) {
					try {
						cursor.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			img_path = uri.getPath();
			System.out.println("------------img_path-----------"+img_path);
		}
		if (CommonMethod.isEmpty(img_path))
			return "";
//			img_path = compressImage(context, img_path, 100);
			System.out.println("------------img_path----=====-------"+img_path);
		return img_path;
	}
	
	/**
	 * 获取屏幕宽度
	 *
	 */
	public static int getScreenWidth(Activity mActivity) {

		DisplayMetrics metric = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);

		return metric.widthPixels;
	}
	
	/**
	 * 压缩照片
	 *
	 * @param mCont
	 * @param filepath
	 * @param quality
	 * @return
	 * @throws java.io.IOException
	 */
	public static String compressImage(Context mCont, String filepath, int quality) throws IOException {
		int degree = CommonMethod.readPictureDegree(filepath);
		System.out.println("degree111111111111"+degree);
		int limite = (int) (1.5 * CommonMethod.getScreenWidth((Activity)mCont));
		// 1. Calculate scale
		int scale = 1;
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filepath, o);
		if (o.outWidth > limite || o.outHeight > limite) {// 1 到4 M 的压成 100k左右
			scale = (int) Math.pow(2.0, (int) Math.round(Math.log(limite / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
			// scale = 2;
		}
		// 2. File -> Bitmap (Returning a smaller image)
		o.inJustDecodeBounds = false;
		o.inSampleSize = scale;
		Bitmap mBitmap = BitmapFactory.decodeFile(filepath, o);
		if (degree != 0) {
			Bitmap b = CommonMethod.rotaingImageView(degree, mBitmap);
			if (b != null && b != mBitmap) {
				mBitmap.recycle();
				mBitmap = b;
				
			}
		}
		// 2.1. Resize Bitmap
		// bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
		// 3. Bitmap -> File
		String fileStr = HRTApplication.cache_root_path + "/meet_zoom_myphotos.jpg";
		if (!CommonMethod.isEmpty(fileStr))
			writeFile(fileStr, mBitmap, quality);
		// 4. Get resized Image File
		// String filePath = getMd5(targetFile.getPath());
		// File compressedImage = mContext.getFileStreamPath(filePath);
		// return compressedImage;
		return fileStr;
	}
	
	/**
	 * 获取图片被旋转的角度
	 *
	 * @param imagePath
	 * @return
	 */
	public static int readPictureDegree(String imagePath) {
		int imageDegree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(imagePath);
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				imageDegree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				imageDegree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				imageDegree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imageDegree;
	}

	/**
	 * 旋转图片
	 *
	 * @param angle
	 * @param mBitmap
	 * @return
	 */
	public static Bitmap rotaingImageView(int angle, Bitmap mBitmap) {

		Matrix matrix = new Matrix();
		matrix.postRotate(angle);

		Bitmap b = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);

		if (b != null && b != mBitmap) {
			mBitmap.recycle();
			mBitmap = b;
		}
		return mBitmap;
	}
	
	public static void writeFile(String filePath, Bitmap bitmap, int quality) {

		if (bitmap == null) {
			return;
		}

		BufferedOutputStream bos = null;

		File file = new File(filePath);

		if (!file.exists()) {

			File parentFile = file.getParentFile();
			if (!parentFile.exists()) {
				file.getParentFile().mkdirs();
			}
		} else {
			file.delete();
		}

		try {

			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bos != null) {
					bitmap.recycle();
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void showDialogPermission(Context context){
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		Dialog dialog = builder.create();
		builder.setTitle("无权限");
		builder.setMessage("分店没有权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		builder.show();
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
	
	public static String getTypeByIndex(int index){
		switch(index){
		case 1:
			return "手动扣减";
		case 2:
			return "消费增加";
		case 3:
			return "手动增加";
		case 4:
			return "消费扣减";
		case 5:
			return "次数增加";
		}
		return "";
	}
}
